import router from "@/router";
import store from "@/store";
import AccessEnum from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";
import accessEnum from "@/access/accessEnum";

router.beforeEach(async (to, from, next) => {

  // @ts-ignore
  let loginUser = store.state.user.loginUser;
  console.log("当前登录用户信息:", loginUser);
  //如果登录用户为空 或者是 登录用户角色为空
  if (!loginUser || !loginUser.userRole) {
    //那么就发请求获取登录用户信息
    await store.dispatch("user/getLoginUser");
    // @ts-ignore
    loginUser = store.state.user.loginUser;
  }

  //获取去往目标路由的所需权限,如果不需要权限,那么默认权限就是不需要登录
  const routeNeedAccess = (to?.meta.accesss as string) ?? AccessEnum.NOT_LOGIN;

  //跳转的页面必须要登录
  if (routeNeedAccess !== AccessEnum.NOT_LOGIN) {
    //如果当前用户还没有登录
    if (!loginUser || !loginUser.userRole || loginUser.userRole === accessEnum.NOT_LOGIN) {
      //那么就必须要去登录才能访问
      next(`/user/login?redirect=${to.fullPath}`);
      return;
    }
    // 如果已经登陆了,那么就进行权限验证
    if (checkAccess(loginUser, routeNeedAccess)) {
      next("/noAuth");
      return;
    }
  }
  next();
});
